package com.example.newsdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 谢汉荣 on 2018/5/27.
 */

public class yuleFragment extends Fragment {
    private RecyclerView recyclerView;
    private MyAdapter adapter;
    private NewsData newsData;
    private Handler handler;

    private String yuleUrl = "http://v.juhe.cn/toutiao/index?type=yule&key=b6f5bc1ab522bd8100ab35b0349a6960";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.yulefragment,null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initHandler();
        initRecyclerView(view);
        getDataFromApi();
    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                adapter.changData(newsData);
                return false;
            }
        });
    }

    private void initRecyclerView(View view) {
        recyclerView = view.findViewById(R.id.list_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MyAdapter(getContext(),newsData);
        recyclerView.setAdapter(adapter);
    }

    private void getDataFromApi() {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(yuleUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("MainActivity","请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String newsDataJsonStr = response.body().string();
                Log.e("MainActivity", "result = " + newsDataJsonStr);
                newsData = new Gson().fromJson(newsDataJsonStr,NewsData.class);

                handler.sendEmptyMessage(1001);

            }
        });
    }
}
